package cn.pet.service.manage.utils;

import cn.pet.service.manage.config.StatusCode;
import cn.pet.service.manage.entity.PetUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @author zwr
 * @version 1.0
 * @description TODO
 * @date 2023/2/17 17:50
 */
@Slf4j
public class SecurityUtil {

    /**
     * 生成BCryptPasswordEncoder密码
     *
     * @param password 密码
     * @return 加密字符串
     */
    public static String encryptPassword(String password)
    {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.encode(password);
    }

    /**
     * 判断密码是否相同
     *
     * @param rawPassword 真实密码
     * @param encodedPassword 加密后字符
     * @return 结果
     */
    public static boolean matchesPassword(String rawPassword, String encodedPassword)
    {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }

    /**
     * 用户ID
     **/
    public static Integer getUserId()
    {
        try
        {
            return getLoginUser().getId();
        }
        catch (Exception e)
        {
            if (log.isDebugEnabled()){
                log.debug("获取用户ID出现异常====》{}",e.getMessage());
            }
           return null;
        }
    }


    /**
     * 获取用户
     **/
    public static PetUser getLoginUser()
    {
        try
        {
            return (PetUser) getAuthentication().getPrincipal();
        }
        catch (Exception e)
        {
            throw new RuntimeException("获取用户信息异常");
        }
    }

    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication()
    {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    public static void main(String[] args) {
        System.out.println(SecurityUtil.encryptPassword("123456"));
    }
}
